#!/usr/bin/env python
#coding=utf-8

import urllib
import types
import time

from flask import request, session, abort

def get_nav_classname(nav):
    """获取导航菜单css class名"""
    if not nav:
        return ''

    if request.endpoint == nav.get('endpoint', ''):
        return ' class=active'

    child_nav_list = nav.get('child', [])
    for child_nav in child_nav_list:
        if request.endpoint == child_nav.get('endpoint', ''):
            return ' class=active'

    return ''


def urlencode(params):
    """url转码"""

    if not params:
        return ''

    _params = params.copy()
    for k,v in params.items():
        if isinstance(v, types.StringType) or isinstance(v, types.UnicodeType):
            _params[k] = v.encode('utf8')

    return urllib.urlencode(_params)


def get_social_time(timestamp):
    """获取社交时间，如：xx分钟前"""
    if timestamp <= 0:
        return ''

    ret = ''
    current_time = int(time.time())
    diff_time = current_time - timestamp
    if diff_time <= 0:
        ret = u'来自未来'
    elif diff_time <= 60:
        ret = u'刚刚'
    elif diff_time <= 1*60*60:
        ret = u'%d分钟前' % int(diff_time/60)
    elif diff_time <= 1*24*60*60:
        ret = u'%d小时前' % int(diff_time/(60*60))
    elif diff_time <= 31*24*60*60:
        ret = u'%d天前' % int(diff_time/(24*60*60))
    elif diff_time <= 365*24*60*60:
        ret = u'%d月前' % int(diff_time/(30*24*60*60))
    else:
        ret = u'%d年前' % int(diff_time/(365*24*60*60))

    return ret

